package view;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import main.Log;

public class ImageFileToImage {
	/**
	 * This map contains the map between a String of a image file name to a BufferedImage
	 */
	private static Map<String, BufferedImage> imageTable = new HashMap<String, BufferedImage>();
	private static BufferedImage dummy = new BufferedImage( 10,10,BufferedImage.TYPE_INT_ARGB );
	
	/**
	 * Private constructor for this singleton
	 */
	private ImageFileToImage() {
		imageTable = new HashMap<String, BufferedImage>();
	}

	/**
	 * This method allows one to retrieve the image that one wants with the associated key. If an
	 * image doesn't exist for that file, a new one is created.
	 * @param imageLocation the location of the image that one wants
	 * @return the cached bufferedImage
	 */
	public static BufferedImage getImage(String imageLocation) {
		imageLocation = (imageLocation != null) ? imageLocation : "" ;
		if( imageTable.containsKey( imageLocation ) ) {
			return imageTable.get( imageLocation );
		}//else, the image has not been loaded yet. Load it and save it in map
		BufferedImage img = null;
		try {
			img = ImageIO.read( new File( imageLocation ) );
		} catch (IOException e) {
			Log.out( Log.VIEW, "{ERROR} Unable to load image: " + imageLocation );
			return dummy;//return dummy so that nothing is painted + nothing gets added to imageTable.
		}
		//now that the image is loaded, save it into the map.
		imageTable.put( imageLocation, img );
		return img;
	}
}
